package org.jeecg.modules.achachievesubjprojitem.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.achachievementsubject.entity.AchAchievementSubject;
import org.jeecg.modules.achachievementsubject.entity.AchAchievementSubjectDemo;
import org.jeecg.modules.achachievementsubject.service.IAchAchievementSubjectService;
import org.jeecg.modules.achachievesubjprojitem.entity.AchAchievementSubjProjItem;
import org.jeecg.modules.achachievesubjprojitem.entity.AchAchievementSubjProjItemDemo;
import org.jeecg.modules.achachievesubjprojitem.mapper.AchAchievementSubjProjItemMapper;
import org.jeecg.modules.achachievesubjprojitem.service.IAchAchievementSubjProjItemService;
import org.jeecg.modules.achachievesubjprojitem.vo.AchAchievementSubjProjItemVo;
import org.jeecg.modules.common.baseentity.BaseApiEntity;
import org.jeecg.modules.common.utils.DateUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description: ach_achievement_subj_proj_item
 * @author: baochangrong
 * @Date:   2022-03-18
 * @Version: V1.0
 */
@Service
public class AchAchievementSubjProjItemServiceImpl extends ServiceImpl<AchAchievementSubjProjItemMapper, AchAchievementSubjProjItem> implements IAchAchievementSubjProjItemService {

    @Autowired
    AchAchievementSubjProjItemMapper achAchievementSubjProjItemMapper;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;
    /** 全部查询 附带关联名称 VoList */
    @Override
    public IPage<AchAchievementSubjProjItemVo> voList(Page<AchAchievementSubjProjItemVo> page,AchAchievementSubjProjItemVo achAchievementSubjProjItemVo){
        List<AchAchievementSubjProjItemVo> achAchievementSubjProjItemVoList = achAchievementSubjProjItemMapper.voList(page,achAchievementSubjProjItemVo);
        return page.setRecords(achAchievementSubjProjItemVoList);
    }

    /** 获取分项成绩数据（根据学生及试卷）
     * getAchAchieveSubjProjItemList
     * */
    @Override
    public IPage<AchAchievementSubjProjItemVo> getAchAchieveSubjProjItemList(Page<AchAchievementSubjProjItemVo> page,String studentId,String examinationPaperId,String tenantId){
        List<AchAchievementSubjProjItemVo> achAchievementSubjProjItemVoList = achAchievementSubjProjItemMapper.getAchAchieveSubjProjItemList(page, studentId,examinationPaperId,tenantId);
        return page.setRecords(achAchievementSubjProjItemVoList);
    }
    public Result<List<Map>> listBatchNumber(AchAchievementSubjProjItemVo achAchievementSubjProjItemVo) {
        List<Map> achAchievementSubjectList = achAchievementSubjProjItemMapper.listBatchNumber(achAchievementSubjProjItemVo);
        return Result.OK(achAchievementSubjectList);
    }

    /**
     * 导出excel
     *
     * @param request
     */
    public ModelAndView exportXlsDemo(HttpServletRequest request, AchAchievementSubjProjItemDemo object, String title, String secondTitle, ISysBaseAPI sysBaseAPI, JSONObject DictList) {
        // Step.1 组装查询条件
        //LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        StringBuffer text = new StringBuffer();
        //年级、考试ID 接口比传，否则返回报错
        if (null == object.getGradeId() || "".equals(object.getGradeId()) || null == object.getExaminationId() || "".equals(object.getExaminationId()) ||
           null == object.getClassIds() || "".equals(object.getClassIds()) || null == object.getExaminationPaperIds() || "".equals(object.getExaminationPaperIds())) {
            new IllegalArgumentException("必选项没有选择，请重新选择！");
            // Step.3  正文
            ExportParams exportParams = new ExportParams(title + "模板", "必选项没有选择，请重新选择！", title);
            exportParams.setType(ExcelType.XSSF);
            exportParams.setImageBasePath(upLoadPath);
            exportParams.setSecondTitleHeight(new Short("10"));
            //map.put("title",exportParams);//表格Title
            ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
            mv.addObject(NormalExcelConstants.PARAMS, exportParams);//表格Title
            return mv;
        }
        //处理年级、考试等批量数据处理
        List<AchAchievementSubjProjItemDemo> achAchievementSubjProjItemDemos = achAchievementSubjProjItemMapper.queryCLassExamData(object);
        // Step.3 说明部分
        DictList.forEach((key, value) -> {
            text.append(key + ": ");
            List<DictModel> dictModelList = sysBaseAPI.getDictItems(value.toString());
            for (DictModel dictModel : dictModelList) {
                text.append(dictModel.getText() + ":" + dictModel.getValue() + ";");

            }
            text.append("\n");
        });
        String secondTitleNew = secondTitle + "\n" + text.toString();

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.3  正文
        ExportParams exportParams = new ExportParams(title + "模板", secondTitleNew, title);
        exportParams.setType(ExcelType.XSSF);
        exportParams.setImageBasePath(upLoadPath);
        exportParams.setSecondTitleHeight(new Short("10"));
        //map.put("title",exportParams);//表格Title
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);//表格Title
        mv.addObject(NormalExcelConstants.CLASS, AchAchievementSubjProjItemDemo.class);//表格对应实体
        mv.addObject(NormalExcelConstants.DATA_LIST, achAchievementSubjProjItemDemos);//数据集合
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public Result<?> importExcelDemo(HttpServletRequest request, HttpServletResponse response, IAchAchievementSubjProjItemService achAchievementSubjProjItemService, BaseApiEntity baseApiEntity) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            String batchNumber = baseApiEntity.getUsername() + DateUtil.getNow("yyyyMMddHHmm");
            long start = System.currentTimeMillis();
            try {
                List<AchAchievementSubjProjItem> list = ExcelImportUtil.importExcel(file.getInputStream(), AchAchievementSubjProjItem.class, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                for (AchAchievementSubjProjItem st : list) {
                    st.setSysOrgCode(baseApiEntity.getSysOrgCode());
                    st.setBatchNumber(batchNumber);
                    st.setCreateTime(DateUtil.getCurrentDate());
                    st.setTenantId(TenantContext.getTenant());
                    st.setCreateBy(baseApiEntity.getUsername());
                    st.setUpdateTime(null);
                    if ("".equals(st.getAchievementStatus()) || null == st.getAchievementStatus() || null == st.getAchiSubjProjItemScore() || "".equals(st.getAchiSubjProjItemScore())) {
                        new IllegalArgumentException("文件中必填项有未填写的。" + st.toString() + "导入失败！请检查数据。");
                        return Result.error("文件中必填项有未填写的。" + st.toString() + "导入失败！请检查数据。");
                    }
                }
                achAchievementSubjProjItemService.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.debug("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }


}
